import cv2
import numpy as np
import os
import json


def showImages(dstDict: dict):
	for item in dstDict.items():
		cv2.imshow(str(item[0]), item[1])
	cv2.waitKey()
	cv2.destroyAllWindows()
	return


def showImage(tag, dst):
	cv2.imshow(tag, dst)
	waitEnd()
	return


def drawRects(rectsParams, canvasShape):
	canvasWidth = canvasShape[0]
	canvasHeight = canvasShape[1]
	canvas = np.zeros([canvasWidth, canvasHeight], np.uint8)
	for (i, (x, y, w, h)) in enumerate(rectsParams):
		r = cv2.rectangle(canvas.copy(), (x, y), (x + w, y + h), (255, 255, 255))
		r = cv2.putText(r.copy(), str(i), (x-20, y+5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 20), 2)
		canvas = cv2.bitwise_or(canvas, r)
	return canvas


def waitEnd():
	cv2.waitKey()
	cv2.destroyAllWindows()
	return


def getContours(src):
	gray = src
	empty = np.zeros([gray.shape[0], gray.shape[1]], np.uint8)
	contours_img = []
	if len(src.shape) == 3:
		gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
	binary = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)[1]
	contours, hierarchy = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
	contours_img = cv2.drawContours(empty, contours, -1, (255, 20, 20))
	return contours, contours_img


def sortContours(contours, method):
	reverse = False
	i = 0

	if method == "right-to-left" or method == "bottom-to-top":
		reverse = True

	if method == "top-to-bottom" or method == "bottom-to-top":
		i = 1
	boundingBoxes = [cv2.boundingRect(c) for c in contours]  # 用一个最小的矩形，把找到的形状包起来x,y,h,w
	(contours, boundingBoxes) = zip(*sorted(zip(contours, boundingBoxes), key=lambda b: b[1][i], reverse=reverse))
	return contours, boundingBoxes


def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
	dim = None
	(h, w) = image.shape[:2]
	if width is None and height is None:
		return image
	if width is None:
		r = height / float(h)
		dim = (int(w * r), height)
	else:
		r = width / float(w)
		dim = (width, int(h * r))
	resized = cv2.resize(image, dim, interpolation=inter)
	return resized


def readJsonFile2Python(path):
	jsonContext = ''
	pythonContext = ''
	if os.path.exists(path):
		with open(path, 'r') as f:
			jsonContext = f.read()
		f.close()
	if jsonContext is not None:
		pythonContext = json.loads(jsonContext)
	return pythonContext
